package com.simou.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.simou.common.R;
import com.simou.dto.SetmealDto;
import com.simou.entity.Category;
import com.simou.entity.Dish;
import com.simou.entity.Setmeal;
import com.simou.service.CategoryService;
import com.simou.service.DishService;
import com.simou.service.SetmealService;
import com.simou.vo.SetmealVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    @Autowired
    CategoryService categoryService;

    @GetMapping("/page")
    public R<Page> getByLimit(int page,int pageSize,String name){
        log.info("page:{},pageSize:{}",page,pageSize);

        Page<Setmeal> pageInfor = new Page<>(page, pageSize);
        Page<SetmealVo> voPageInfor = new Page<>(page, pageSize);

//        根据名字和分页查询setmeal表
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        setmealService.page(pageInfor,queryWrapper);

//        根据记录中的categoryId查询category表
        List<Setmeal> records = pageInfor.getRecords();

        ArrayList<SetmealVo> setmealVos = new ArrayList<>();
        for (Setmeal record : records) {
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //  将setmeal表和category表的信息放入SetmealVos列表中
            SetmealVo setmealVo = new SetmealVo();
            BeanUtils.copyProperties(record,setmealVo);
            setmealVo.setCategoryName(category.getName());
            setmealVos.add(setmealVo);
        }

//        将分页信息和查询数据放入voPageInfor中
        BeanUtils.copyProperties(pageInfor,voPageInfor);
        voPageInfor.setRecords(setmealVos);

        return R.success(voPageInfor);
    }

    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)   // 删除所有setmealCache缓存
    public R<String> addSetmeal(@RequestBody SetmealDto setmealDto){
        log.info("添加套餐：{}",setmealDto);
        setmealService.saveWithSetmealDish(setmealDto);
        return R.success("添加套餐成功");

    }

    // 修改套餐页面数据回显
    @GetMapping("/{id}")
    public R<SetmealVo> getById(@PathVariable("id") Long id){
        log.info("查询套餐id：{}",id);
        SetmealVo setmealVo = setmealService.getByIdWithSetmealDishAndCategory(id);
        return R.success(setmealVo);
    }

//    修改套餐售卖状态
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)   // 删除所有setmealCache缓存
    public R<String> changeStatus(@PathVariable Long status,String ids){
        log.info("修改状态 status:{},ids:{}",status,ids);
        String[] idList = ids.split(",");

        for (String id : idList) {
            UpdateWrapper<Setmeal> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",Long.parseLong(id))
                    .set("status",status);
            setmealService.update(updateWrapper);
            // 由于MP会自动把price属性更新为0.0,此处不使用updateById
//            setmealService.updateById(setmeal);
        }

        return R.success("修改状态成功");
    }

    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)   // 删除所有setmealCache缓存
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("修改页面setmealDto:{}",setmealDto);
        setmealService.updateWithSetmealDish(setmealDto);
        return R.success("修改成功");
    }

    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)   // 删除所有setmealCache缓存
    public R<String> delete(String ids){
        log.info("删除页面 ids:{}",ids);
        String[] idList = ids.split(",");

        for (String id : idList) {
            setmealService.deleteWithSetmealDish(Long.parseLong(id));
        }

        return R.success("删除成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status",unless = "#result.data.size==0")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
